<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="24">
          <a-form-item label="排序" v-bind="validateInfos.sorts">
	          <a-input-number v-model:value="formData.sorts" placeholder="请输入排序" style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="父级节点" v-bind="validateInfos.pid">
            <j-tree-select
              placeholder="请选择父级节点"
              v-model:value="formData.pid"
              dict="medication_shop,type_name,id"
              pidField="pid"
              pidValue="0"
              hasChildField="has_child"
              :disabled="disabled">
            </j-tree-select>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否上架" v-bind="validateInfos.isValidate">
	          <j-dict-select-tag v-model:value="formData.isValidate" dictCode="yes_no" placeholder="请选择是否上架" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="产业名称" v-bind="validateInfos.goodsType">
	          <j-dict-select-tag v-model:value="formData.goodsType" dictCode="shop_type" placeholder="请选择产业名称" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="专业名称" v-bind="validateInfos.typeName">
            <a-input v-model:value="formData.typeName" placeholder="请输入专业名称" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="价格" v-bind="validateInfos.price">
	          <a-input-number v-model:value="formData.price" placeholder="请输入价格" style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="单位" v-bind="validateInfos.unit">
            <a-input v-model:value="formData.unit" placeholder="请输入单位" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="分类图片" v-bind="validateInfos.pic">
	          <j-image-upload :fileMax=6 v-model:value="formData.pic" :disabled="disabled"></j-image-upload>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="商品详情" v-bind="validateInfos.details">
	          <j-editor v-model:value="formData.details" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="关联药店" v-bind="validateInfos.shop">
            <a-input v-model:value="formData.shop" placeholder="请输入关联药店" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="库存" v-bind="validateInfos.num">
	          <a-input-number v-model:value="formData.num" placeholder="请输入库存" style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="商品编号" v-bind="validateInfos.productCode">
            <a-input v-model:value="formData.productCode" placeholder="请输入商品编号" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="商品条形码" v-bind="validateInfos.arcode">
            <a-input v-model:value="formData.arcode" placeholder="请输入商品条形码" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="商品追溯码" v-bind="validateInfos.traceCode">
            <a-input v-model:value="formData.traceCode" placeholder="请输入商品追溯码" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="商品二维码" v-bind="validateInfos.ecode">
            <a-input v-model:value="formData.ecode" placeholder="请输入商品二维码" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="型号" v-bind="validateInfos.model">
            <a-input v-model:value="formData.model" placeholder="请输入型号" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="商品规格" v-bind="validateInfos.productPecs">
            <a-input v-model:value="formData.productPecs" placeholder="请输入商品规格" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="规格" v-bind="validateInfos.specification">
            <a-input v-model:value="formData.specification" placeholder="请输入规格" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="材质" v-bind="validateInfos.material">
            <a-input v-model:value="formData.material" placeholder="请输入材质" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="含量" v-bind="validateInfos.packagingUnit">
            <a-input v-model:value="formData.packagingUnit" placeholder="请输入含量" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="外观包装" v-bind="validateInfos.externalPack">
            <a-input v-model:value="formData.externalPack" placeholder="请输入外观包装" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="销售单价" v-bind="validateInfos.sellingPrice">
	          <a-input-number v-model:value="formData.sellingPrice" placeholder="请输入销售单价" style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="销售折扣率" v-bind="validateInfos.salesRate">
	          <a-input-number v-model:value="formData.salesRate" placeholder="请输入销售折扣率" style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="销售折扣后单价" v-bind="validateInfos.discountPrice">
	          <a-input-number v-model:value="formData.discountPrice" placeholder="请输入销售折扣后单价" style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="销售小计金额" v-bind="validateInfos.subtotalAmount">
            <a-input v-model:value="formData.subtotalAmount" placeholder="请输入销售小计金额" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="生产日期" v-bind="validateInfos.productionDate">
		        <a-date-picker placeholder="请选择生产日期" v-model:value="formData.productionDate" value-format="YYYY-MM-DD"  style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="使用期限" v-bind="validateInfos.serviceLife">
		        <a-date-picker placeholder="请选择使用期限" v-model:value="formData.serviceLife" value-format="YYYY-MM-DD"  style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="失效日期" v-bind="validateInfos.expiryDate">
		        <a-date-picker placeholder="请选择失效日期" v-model:value="formData.expiryDate" value-format="YYYY-MM-DD"  style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="近效期示警标签" v-bind="validateInfos.warningLabel">
            <a-input v-model:value="formData.warningLabel" placeholder="请输入近效期示警标签" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="专利等知识产权说明" v-bind="validateInfos.propertyNotes">
            <a-input v-model:value="formData.propertyNotes" placeholder="请输入专利等知识产权说明" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="产品说明书" v-bind="validateInfos.productManual">
            <a-input v-model:value="formData.productManual" placeholder="请输入产品说明书" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="产品注册许可证编号" v-bind="validateInfos.licenseNumber">
            <a-input v-model:value="formData.licenseNumber" placeholder="请输入产品注册许可证编号" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="生产批号 " v-bind="validateInfos.serialNumber">
            <a-input v-model:value="formData.serialNumber" placeholder="请输入生产批号 " :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="质量层次" v-bind="validateInfos.qualityLevel">
            <a-input v-model:value="formData.qualityLevel" placeholder="请输入质量层次" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="生产厂家" v-bind="validateInfos.manufacturer">
            <a-input v-model:value="formData.manufacturer" placeholder="请输入生产厂家" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="产地" v-bind="validateInfos.originPlace">
	          <j-dict-select-tag v-model:value="formData.originPlace" dictCode="citizen" placeholder="请选择产地" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="厂家生产许可证编号" v-bind="validateInfos.productionLicense">
            <a-input v-model:value="formData.productionLicense" placeholder="请输入厂家生产许可证编号" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="采购人资质要求" v-bind="validateInfos.purchaseRequirements">
	          <j-dict-select-tag v-model:value="formData.purchaseRequirements" dictCode="buy_auth" placeholder="请选择采购人资质要求" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="贮存要求" v-bind="validateInfos.storageRequirements">
            <a-input v-model:value="formData.storageRequirements" placeholder="请输入贮存要求" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="堆放要求" v-bind="validateInfos.stackingRequirements">
            <a-input v-model:value="formData.stackingRequirements" placeholder="请输入堆放要求" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="搬运要求" v-bind="validateInfos.handlingRequirements">
            <a-input v-model:value="formData.handlingRequirements" placeholder="请输入搬运要求" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="销售前库存数量" v-bind="validateInfos.salesStorage">
	          <a-input-number v-model:value="formData.salesStorage" placeholder="请输入销售前库存数量" style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="销售数量" v-bind="validateInfos.salesQuantity">
            <a-input v-model:value="formData.salesQuantity" placeholder="请输入销售数量" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="当前库存数量" v-bind="validateInfos.currentStorage">
            <a-input v-model:value="formData.currentStorage" placeholder="请输入当前库存数量" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="紧急程度" v-bind="validateInfos.urgencyLevel">
            <a-input v-model:value="formData.urgencyLevel" placeholder="请输入紧急程度" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="非工作时段" v-bind="validateInfos.nonworkingHours">
            <a-input v-model:value="formData.nonworkingHours" placeholder="请输入非工作时段" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="节假日" v-bind="validateInfos.holidays">
            <a-input v-model:value="formData.holidays" placeholder="请输入节假日" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label=" 是否当面签收" v-bind="validateInfos.issign">
            <a-input v-model:value="formData.issign" placeholder="请输入 是否当面签收" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否审核" v-bind="validateInfos.isAuth">
	          <j-dict-select-tag v-model:value="formData.isAuth" dictCode="yn" placeholder="请选择是否审核" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否要求安装" v-bind="validateInfos.isinstall">
            <a-input v-model:value="formData.isinstall" placeholder="请输入是否要求安装" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="安装具体要求" v-bind="validateInfos.installRequirement">
            <a-input v-model:value="formData.installRequirement" placeholder="请输入安装具体要求" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否要求配件" v-bind="validateInfos.isAccessories">
            <a-input v-model:value="formData.isAccessories" placeholder="请输入是否要求配件" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="配件具体要求" v-bind="validateInfos.acceRequirement">
            <a-input v-model:value="formData.acceRequirement" placeholder="请输入配件具体要求" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="备注" v-bind="validateInfos.remarks">
            <a-input v-model:value="formData.remarks" placeholder="请输入备注" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="商品上架申请单位" v-bind="validateInfos.applicationUnit">
            <a-input v-model:value="formData.applicationUnit" placeholder="请输入商品上架申请单位" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="商品上架申请单位对接人" v-bind="validateInfos.contactPerson">
            <a-input v-model:value="formData.contactPerson" placeholder="请输入商品上架申请单位对接人" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="规格编码" v-bind="validateInfos.standardCode">
            <a-input v-model:value="formData.standardCode" placeholder="请输入规格编码" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否直营" v-bind="validateInfos.isDirect">
            <a-input v-model:value="formData.isDirect" placeholder="请输入是否直营" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, unref, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JTreeSelect from '/@/components/Form/src/jeecg/components/JTreeSelect.vue';
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import JEditor from '/@/components/Form/src/jeecg/components/JEditor.vue';
  import { getValueType } from '/@/utils';
  import {loadTreeData, saveOrUpdateDict} from '../MedicationShop.api';
  import { Form } from 'ant-design-vue';
  
  const useForm = Form.useForm;
  const formRef = ref();
  const isUpdate = ref(true);
  const expandedRowKeys = ref([]);
  const treeData = ref([]);
  const pidField = ref<string>('pid');
  const emit = defineEmits(['register', 'ok']);
  let model: Nullable<Recordable> = null;
  const formData = reactive<Record<string, any>>({
    id: '',
    sorts: undefined,
    pid: '',   
    isValidate: '1',   
    goodsType: '',   
    typeName: '',   
    price: undefined,
    unit: '',   
    pic: '',   
    details: '',   
    shop: '',   
    num: undefined,
    productCode: '',   
    arcode: '',   
    traceCode: '',   
    ecode: '',   
    model: '',   
    productPecs: '',   
    specification: '',   
    material: '',   
    packagingUnit: '',   
    externalPack: '',   
    sellingPrice: undefined,
    salesRate: undefined,
    discountPrice: undefined,
    subtotalAmount: '',   
    productionDate: '',   
    serviceLife: '',   
    expiryDate: '',   
    warningLabel: '',   
    propertyNotes: '',   
    productManual: '',   
    licenseNumber: '',   
    serialNumber: '',   
    qualityLevel: '',   
    manufacturer: '',   
    originPlace: '1',   
    productionLicense: '',   
    purchaseRequirements: '1',   
    storageRequirements: '',   
    stackingRequirements: '',   
    handlingRequirements: '',   
    salesStorage: undefined,
    salesQuantity: '',   
    currentStorage: '',   
    urgencyLevel: '',   
    nonworkingHours: '',   
    holidays: '',   
    issign: '',   
    isAuth: '',   
    isinstall: '',   
    installRequirement: '',   
    isAccessories: '',   
    acceRequirement: '',   
    remarks: '',   
    applicationUnit: '',   
    contactPerson: '',   
    standardCode: '',   
    isDirect: '',   
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: ()=>{} },
    formBpm: { type: Boolean, default: true }
  });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  
  /**
   * 新增
   */
  function add(obj = {}) {
    edit(obj);
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(async () => {
      resetFields();
      expandedRowKeys.value = [];
      treeData.value = await loadTreeData({ async: false, pcode: '' });
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData,tmpData);
      model = tmpData
    });
  }

  /**
   * 根据pid获取展开的节点
   * @param pid
   * @param arr
   */
  function getExpandKeysByPid(pid, arr) {
    if (pid && arr && arr.length > 0) {
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].key == pid && unref(expandedRowKeys).indexOf(pid) < 0) {
          expandedRowKeys.value.push(arr[i].key);
          getExpandKeysByPid(arr[i]['parentId'], unref(treeData));
        } else {
          getExpandKeysByPid(pid, arr[i].children);
        }
      }
    }
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    if (formData.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in formData) {
      //如果该数据是数组并且是字符串类型
      if (formData[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          formData[data] = formData[data].join(',');
        }
      }
    }
    await saveOrUpdateDict(formData, isUpdate.value)
      .then(async (res) => {
        if (res.success) {
          await getExpandKeysByPid(formData['pid'], unref(treeData));
          delete formData['children'];
          emit('ok', {
            isUpdate: unref(isUpdate),
            values: { ...formData },
            expandedArr: unref(expandedRowKeys).reverse(),
            // 是否更改了父级节点
            changeParent: model != null && model['pid'] != formData['pid'],
          });
          createMessage.success(res.message);
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  /**
   * 值改变事件触发
   * @param key
   * @param value
   */
  function handleFormChange(key, value) {
    formData[key] = value;
  }

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    height: 500px !important;
    overflow-y: auto;
    padding: 14px;
  }
</style>
